//
//  SIAPViewController.swift
//  Source
//
//  Created by Toj on 5/10/22.
//

import UIKit
// 1.首先集成导入支付包
// 集成: General -> Frameworks -> + StoreKit
// 导入
import StoreKit

enum IAPPurchType: Int {
    case success // 购买成功
    case failed  // 购买失败
    case cancel  // 取消购买
    case verFailed // 订单校验失败
    case verSuccess // 订单校验成功
    case notArrow  // 不允许内购
}

class STViewController: UIViewController {
    
    private var selectedProductID = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        setupUI()
        
        // 2. 初始化内购支付服务
        SKPaymentQueue.default().add(self)
    }
    
    private func setupUI() {
        view.addSubview(payButton)
        payButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
    }
    
    @objc private func didTapPay() {
        // 3. 判断app是否允许apple支付
        let canPayments = SKPaymentQueue.canMakePayments()
        guard canPayments else {
            print("-->toj: 苹果现在不能支付, 请稍后再试")
            return
        }
        
        // 4. 请求苹果后台商品列表
        // 开发者后台配置的内购产品ID
        let productID = "com.521it.source_iOS" + "01"
        requestAppleProduct(productID)
    }
    
    // 4. 请求苹果后台商品列表
    private func requestAppleProduct(_ productID: String) {
        selectedProductID = productID
        var products: Set<String> = []
        products.insert(productID)
        // 初始化请求
        let request = SKProductsRequest(productIdentifiers: products)
        request.delegate = self;
        // 开始请求
        request.start()
    }
    
    private lazy var payButton: UIButton = {
        let view = UIButton()
        view.setTitle("支付", for: .normal)
        view.backgroundColor = .red
        view.addTarget(self, action: #selector(didTapPay), for: .touchUpInside)
        return view
    }()
}

extension STViewController: SKProductsRequestDelegate {
    
    // 5. 接收到产品的返回信息,然后用返回的商品信息进行发起购买请求
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let products = response.products
        guard products.count > 0 else {
            print("-->toj: 服务器没有产品")
            return
        }
        
        // 选择的产品
        var requestProduct: SKProduct? = nil
        
        // 5.1 遍历产品从中找到选择的产品
        for product in products {
            print("-->toj: description: \(product.description)")
            print("-->toj: localizedTitle: \(product.localizedTitle)")
            print("-->toj: localizedDescription: \(product.localizedDescription)")
            print("-->toj: price: \(product.price)")
            print("-->toj: productIdentifier: \(product.productIdentifier)")
            
            if selectedProductID != product.productIdentifier { continue }
            
            requestProduct = product
            break
        }
        
        guard let product = requestProduct else {
            print("-->toj: 没有找到选择的产品")
            return
        }
        
        // 5.2 发送购买请求
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }
    
    // 请求失败
    func request(_ request: SKRequest, didFailWithError error: Error) {
        print("-->toj: error:%@", error)
    }
    
    // 反馈请求的产品信息结束后
    func requestDidFinish(_ request: SKRequest) {
        print("-->toj: requestDidFinish")
    }
}

extension STViewController: SKPaymentTransactionObserver {
    // 6. 监听购买结果
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                print("-->toj: 交易完成")
                break;
            case .purchasing:
                print("-->toj: 商品添加进列表")
                break;
            case .restored:
                print("-->toj: 已经购买过商品")
                SKPaymentQueue.default().finishTransaction(transaction)
                break;
            case .failed:
                print("-->toj: 交易失败")
                SKPaymentQueue.default().finishTransaction(transaction)
                break;
            default:
                break;
            }
        }
    }
}

extension STViewController {
    // 7. 请求服务器, 服务器验证支付信息
    // 当交易结束后还要去appstore上验证支付信息是否都正确,只有所有都正确后,我们就可以给用户方法我们的虚拟物品了.
    func completeTransaction(transaction: SKPaymentTransaction) {
        guard let url = Bundle.main.appStoreReceiptURL else {
            print("-->toj: 苹果没有返回交易凭证")
            return
        }
        
        guard let receiptData = NSData(contentsOf: url) else {
            print("-->toj: 本地没有找到交易凭证")
            return
        }
        // 把当前的凭证信息不用app端验证,
        // 发送给我们服务器, 让服务器验证凭证的真实性, 返回给我们最后的验证结果
    }
}
